import webview
import json
import os
import sys
import asyncio

# Add the parent directory to Python's path so imports work correctly
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)

from core.conversation_manager import ConversationManager
from config.config_manager import get_api_key, save_config, get_available_models, get_model
import threading
import queue

class ApiInterface:
    def __init__(self):
        # 初始化对话管理器
        self.conversation_manager = None
        self.system_message = "你是一名智能助手，善于解决问题。"
        self.use_tools = False
        self.mcp_config = None
        self.init_conversation_manager()
        
        # 创建消息队列和事件循环
        self.message_queue = queue.Queue()
        self.loop = None
        self.thread = None
        self.start_background_loop()
        
    def start_background_loop(self):
        """启动后台事件循环线程"""
        def run_event_loop():
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)
            self.loop.run_forever()
            
        self.thread = threading.Thread(target=run_event_loop, daemon=True)
        self.thread.start()
        
    def init_conversation_manager(self):
        """初始化对话管理器"""
        self.conversation_manager = ConversationManager(
            system_message=self.system_message,
            use_tools=self.use_tools,
            mcp_config=self.mcp_config
        )
        return {"success": True}
    
    def get_config(self):
        """获取当前配置信息"""
        models_info = self.conversation_manager.get_available_models_info()
        current_model = self.conversation_manager.model
        current_provider = self.conversation_manager.provider
        
        # Ensure current_model has a default value
        if not current_model:
            if current_provider == 'qwen':
                current_model = 'qwen3-235b-a22b'
            else:
                current_model = 'deepseek-chat'
        
        return {
            "success": True,
            "api_keys": {
                "deepseek": get_api_key("deepseek"),
                "qwen": get_api_key("qwen")
            },
            "available_models": models_info,
            "current_model": current_model,
            "current_provider": current_provider or 'deepseek',
            "system_message": self.system_message,
            "use_tools": self.use_tools
        }
    
    def save_config(self, provider, api_key, model_name, use_tools=False):
        """保存API配置"""
        try:
            # 更新配置文件
            save_config(provider, api_key)
            
            # 更新是否使用工具
            self.use_tools = use_tools
            
            # 更新当前会话配置
            success = self.conversation_manager.set_model(model_name)
            
            if not success:
                return {"success": False, "error_message": f"模型 {model_name} 设置失败"}
                
            return {"success": True}
        except Exception as e:
            return {"success": False, "error_message": str(e)}
    
    def set_system_prompt(self, system_prompt):
        """设置系统提示词"""
        try:
            self.system_message = system_prompt
            # 清除旧对话历史，创建新对话
            self.conversation_manager = ConversationManager(
                system_message=system_prompt,
                model=self.conversation_manager.model,
                use_tools=self.use_tools,
                mcp_config=self.mcp_config
            )
            return {"success": True}
        except Exception as e:
            return {"success": False, "error_message": str(e)}
    
    def _limit_conversation_history(self, max_messages=20):
        """限制会话历史长度，保留系统消息和最近的用户消息与回复"""
        messages = self.conversation_manager.get_conversation_history()
        if len(messages) <= max_messages:
            return
        
        # 保留所有系统消息
        system_messages = [msg for msg in messages if msg["role"] == "system"]
        
        # 获取非系统消息
        non_system = [msg for msg in messages if msg["role"] != "system"]
        
        # 计算需要保留的非系统消息数量
        keep_count = max_messages - len(system_messages)
        
        # 保留最近的消息
        kept_messages = system_messages + non_system[-keep_count:] if keep_count > 0 else system_messages
        
        # 更新会话历史
        self.conversation_manager.messages = kept_messages

    def send_message(self, message):
        """发送消息并获取响应（非阻塞）"""
        try:
            # 添加用户消息
            self.conversation_manager.add_user_message(message)
            
            # 限制历史长度
            self._limit_conversation_history(max_messages=20)
            
            # 在后台线程中处理请求
            def process_request():
                try:
                    # 添加超时控制到API调用
                    future = asyncio.run_coroutine_threadsafe(
                        self.conversation_manager.get_response(), 
                        self.loop
                    )
                    try:
                        # 添加30秒超时，避免无限等待
                        response = future.result(timeout=30)
                    except asyncio.TimeoutError:
                        # 超时处理
                        self.message_queue.put({
                            "success": False, 
                            "error_message": "请求超时，服务器响应时间过长"
                        })
                        return
                        
                    # 处理响应并将结果放入队列
                    if response.get("success"):
                        result = {
                            "success": True,
                            "content": response.get("content", ""),
                            "tool_calls": response.get("tool_calls", []),
                            "prompt_tokens": response.get("prompt_tokens", 0),
                            "completion_tokens": response.get("completion_tokens", 0),
                            "total_prompt_tokens": response.get("total_prompt_tokens", 0),
                            "total_completion_tokens": response.get("total_completion_tokens", 0),
                            "api_call_count": response.get("api_call_count", 1),
                            "completed": True
                        }
                    else:
                        result = response
                        
                    # 将结果放入队列
                    self.message_queue.put(result)
                    
                except Exception as e:
                    import traceback
                    print(f"处理请求出错: {str(e)}")
                    print(traceback.format_exc())
                    self.message_queue.put({"success": False, "error_message": str(e)})
            
            # 启动处理线程并返回初始响应
            threading.Thread(target=process_request, daemon=True).start()
            return {"success": True, "processing": True}
            
        except Exception as e:
            # 添加详细错误日志
            import traceback
            print(f"发送消息出错: {str(e)}")
            print(traceback.format_exc())
            return {"success": False, "error_message": str(e)}
    
    def get_response_chunk(self):
        """获取响应片段（用于流式输出）"""
        try:
            # 非阻塞方式检查队列
            try:
                # 尝试从队列获取响应，不等待
                response = self.message_queue.get_nowait()
                return response
            except queue.Empty:
                # 队列为空，表示处理尚未完成
                return {"success": True, "processing": True}
        except Exception as e:
            import traceback
            print(f"获取响应片段出错: {str(e)}")
            print(traceback.format_exc())
            return {"success": False, "error_message": str(e)}
    
    def clear_chat(self):
        """清空对话历史"""
        try:
            self.conversation_manager.clear_history()
            return {"success": True}
        except Exception as e:
            return {"success": False, "error_message": str(e)}
    
    def get_conversation_list(self):
        """获取可用的对话历史文件列表"""
        try:
            conversations = self.conversation_manager.get_available_conversations()
            return {"success": True, "conversations": conversations}
        except Exception as e:
            return {"success": False, "error_message": str(e)}
    
    def load_conversation(self, file_name):
        """加载对话历史"""
        try:
            success = self.conversation_manager.load_conversation(file_name)
            if success:
                messages = self.conversation_manager.get_conversation_history()
                # 更新系统消息
                for msg in messages:
                    if msg["role"] == "system":
                        self.system_message = msg["content"]
                        break
                return {"success": True, "messages": messages}
            else:
                return {"success": False, "error_message": "加载对话历史失败"}
        except Exception as e:
            return {"success": False, "error_message": str(e)}
    
    def save_conversation(self, file_name):
        """保存对话历史"""
        try:
            success = self.conversation_manager.save_conversation(file_name)
            if success:
                return {"success": True}
            else:
                return {"success": False, "error_message": "保存对话历史失败"}
        except Exception as e:
            return {"success": False, "error_message": str(e)}
    
    def toggle_tools(self, enabled):
        """开关工具支持"""
        try:
            self.use_tools = enabled
            
            # 如果启用工具，配置MCP
            if enabled:
                self.mcp_config = {
                    "mcpServers": {
                        "GYCDWcq578JMgRTd34B0_": {
                            "name": "自定义seatable MCP 服务器",
                            "type": "stdio",
                            "description": "",
                            "isActive": True,
                            "command": "uv",
                            "args": [
                                "--directory",
                                os.path.abspath(os.path.join(os.path.dirname(__file__), '..')),
                                "run", "tools/SeaTable_server.py"
                            ]
                        }
                    }
                }
            else:
                self.mcp_config = None
                
            # 重新初始化对话管理器
            self.conversation_manager = ConversationManager(
                system_message=self.system_message,
                use_tools=self.use_tools,
                mcp_config=self.mcp_config
            )
            
            return {"success": True}
        except Exception as e:
            return {"success": False, "error_message": str(e)}

# 创建窗口并启动应用
if __name__ == '__main__':
    # 获取ui.html的绝对路径
    html_path = os.path.abspath('ui/ui.html')
    
    # 创建API接口实例
    api = ApiInterface()
    
    # 创建窗口并传入API接口
    window = webview.create_window('AI智能体界面', html_path, js_api=api, width=1200, height=800)
    
    # 启动webview
    webview.start(debug=True)
